import React, {Component} from 'react'
import axios from 'axios'
import Line2Chart from '../components/Line2Chart'
import Box from '../components/Box'
import './index.css'

class App extends Component {

    filters = [
        {
            label: 'cpu占用率',
            name: 'cpuPercent',
            type: 'array'
        },
        {
            label: 'cpu占用率平均值',
            name: 'cpuPercent',
            type: 'average'
        },
        {
            label: '虚拟内存占用',
            name: 'virtualMemoryPercent'
        },
        {
            label: '交换内存占用',
            name: 'swapPercent'
        },
        {
            label: '出站字节',
            name: 'networkSentBytes'
        },
        {
            label: '进站字节',
            name: 'networkRecvBytes'
        },
        {
            label: '读字节',
            name: 'diskReadBytes'
        },
        {
            label: '写字节',
            name: 'diskWriteBytes'
        },
    ]

    constructor() {
        super(...arguments)

        this.state = {
            selectFilterIndex: 0,
            selectType: 0
        }
    }

    componentDidMount() {
        // 拉取图表数据
        this.fetchLineChartData()
    }

    // echart 文档 https://echarts.baidu.com/
    async fetchLineChartData() {
        // 请求接口获取图表数据
        const response = await axios.get('https://www.easy-mock.com/mock/5ca9efd1646ec411e7a920cc/one_test/getAllJobs')

        // response.data 是接口返回的json数据（已自动转换为json对象）
        const {status, data: chartData} = response.data

        if (status === 0) {
            this.setState({
                chartData
            })
        }
    }

    getRelativeTime(time, baseTime){
        return Math.round((new Date(time).getTime() - new Date(baseTime).getTime()) / 1000 / 60)
    }

    // echart 文档 https://echarts.baidu.com/
    getChartProps(jobs) {
        const sumInstanceMap = {}

        jobs.forEach(({computer: computers, jobIdx})=>{
            computers.forEach(({instances},computerIdx)=>{
                instances.forEach((instance,instanceIdx)=>{
                    const key = instanceIdx
                    let {time, ...remain} = instance
                    const sumInstance = sumInstanceMap[key] = sumInstanceMap[key]||{time: this.getRelativeTime(time, jobs[0].computer[0].instances[0].time)}
                    Object.keys(remain).forEach(valueKey=>{
                        sumInstance[valueKey]= sumInstance[valueKey]||0

                        let value = instance[valueKey]
                        if(Object.prototype.toString.call(value) === '[object Object]'){
                            const values = Object.values(value)
                            value = values.reduce((sum, val)=>sum+(parseFloat(val)/values.length), 0)
                        } else {
                            value = parseFloat(value)
                        }

                        sumInstance[valueKey]+=value/jobs.length/jobs[0].computer.length
                    })
                })
            })
        })

        console.log('sumInstanceMap', sumInstanceMap)

        const schema = [
            {name: '百分比', index: 0, text: '日期', max: 100},
            {name: 'Mb/s', index: 1, text: '等级', max: 1000}
        ]

        const keysMap = {
            'cpuPercent':{
                title: 'cpuPercent',
                schema: schema[0]
            },
            'virtualMemoryPercent':{
                title: 'virtualMemoryPercent',
                schema: schema[1]
            },
            'swapPercent':{
                title: 'swapPercent',
                schema: schema[1]
            },
            'networkSentBytes':{
                title: 'networkSentBytes',
                schema: schema[1]
            },
        }

        const legendData = Object.values(keysMap).map(i=>i.title)


        const lineStyle = {
            normal: {
                width: 1,
                opacity: 0.5
            }
        }

        const option = {
            tooltip : {
                trigger : 'axis'
            },
            grid : {
                right : '20%'
            },
            toolbox : {
                feature : {
                    dataView : {
                        show : false,
                        readOnly : false
                    },
                    restore : {
                        show : false
                    },
                    saveAsImage : {
                        show : false
                    }
                }
            },
            legend : {
                data : legendData
            },
            xAxis : [ {
                type : 'category',
                axisTick : {
                    alignWithLabel : true
                },
                data : Object.values(sumInstanceMap).map(i=>i.time)
            } ],
            yAxis : [
                {
                    type : 'value',
                    name : '百分比',
                    min : 0,
                    max : 100,
                    position : 'left',
                    axisLine : {
                        lineStyle : {}
                    },
                    axisLabel : {
                        formatter : '{value}'
                    }
                },
                {
                    type : 'value',
                    name : 'Mb/s',
                    min : 0,
                    max : 11000,
                    position : 'right',
                    axisLine : {
                        lineStyle : {}
                    },
                    axisLabel : {
                        formatter : '{value}'
                    }
                },
            ],
            series : [
                ...Object.keys(keysMap).map(key=>({
                    name: keysMap[key].title,
                    type: 'line',
                    yAxisIndex: keysMap[key].schema.index,
                    lineStyle: lineStyle,
                    data: Object.values(sumInstanceMap).map(i=>i[key].toFixed(1))
                }))
            ]
        }
        console.log('option', option)
        return option
    }

    render() {
        const {selectFilterIndex, chartData} = this.state
        let chartProps
        const filter = this.filters[selectFilterIndex]
        let typeList = null
        if (chartData) {
            const {computer: computerList = []} = this.state.chartData
            if (filter.type === 'array') {
                typeList = computerList.map(i => i.ip)
            }
            chartProps = this.getChartProps(chartData, filter);
        }
        return (
            <div className="App">
                <Box title="集群八项数据基本数据曲线">
                    {chartProps && <Line2Chart className={typeList ? 'line-chart-array' : ''} chartProps={chartProps}/>}
                </Box>
            </div>
        );
    }
}

export default App;
